/**
 * 
 */
package utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import exception.DataAccessException;

/**
 * @ClassName: DBUtils
 * @Description: 
 * @author Hongming Wu
 * @date 2013-11-27 
 *
 */
public class DBUtils {
	
//	private static final String CONN_STR="jdbc:mysql://localhost:3306/securityDB";
//	private static final String USERNAME="root";
//	private static final String PWD="123";
//		
//	private static DBUtils me=new DBUtils();
//	
//	private DBUtils() {}
//	
//	public static DBUtils getInstance()
//	{
//		return me;
//	}
//	
//	public Connection getConn()
//	{
//		
//		Connection conn=null;
//		
//		try {
//
//			Class.forName("com.mysql.jdbc.Driver");
//			conn=DriverManager.getConnection(CONN_STR, USERNAME, PWD);
//		} catch (ClassNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} 
//		
//		return conn;
//		
//	}
//	
//
//	public void ReleaseRes(Connection conn,PreparedStatement pstmt,ResultSet rset)
//	{
//		try{
//		  if(rset!=null) rset.close();
//		  if(pstmt!=null) pstmt.close();
//		  if(conn!=null)  conn.close();
//		}catch(SQLException e)
//		{
//			e.printStackTrace();
//		}
//	}
	

	private static ThreadLocal<Connection> threadStore = new ThreadLocal<Connection>();

	private static DBUtils me = new DBUtils();

	private DBUtils() {
	}

	public static DBUtils getInstance() {
		return me;
	}

	static {
		try {
			Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public synchronized Connection getConn() {
		Connection conn = threadStore.get();

		if (null == conn) {
			try {
				conn = DriverManager.getConnection("proxool.securitysys-ds");
				threadStore.set(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return conn;
	}

	public void ReleaseRes(Connection conn, PreparedStatement pstmt,
			ResultSet rset) {
		try {
//			if (rset != null) {
//				rset.close();
//			}
			if (pstmt != null) {
				pstmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public synchronized void releaseConn(Connection conn) {
		if (null != conn) {
			threadStore.remove();
			try {
				conn.close();
			} catch (SQLException e) {
				throw new DataAccessException(e.getMessage());
			}
		}
	}

}